// 支付记录类型定义
export interface PaymentRecord {
  id: string
  member_id: string
  payment_type: string
  amount: string
  balance: string
  currency: string
  payment_channel: string
  remark?: string
  status: string
  payment_date: string
  transaction_id: string
  create_time: string
  operator: string
  related_record_id?: string
  is_revoked: number
  created_at?: string
}

// 费率设置类型定义
export interface RateSettings {
  id: string
  member_id: string
  exchange_rate?: string | null
  service_fee?: string | null
  service_fee_ranges?: string | null // JSON字符串格式
  service_rate?: string | null
  service_rate_sites?: string | null // JSON字符串格式
  deposit_ratio?: string | null
  deposit_ratio_sites?: string | null // JSON字符串格式
  created_at: string
  updated_at: string
}

// IndexedDB 数据库管理
class PaymentDatabase {
  private dbName = 'PaymentRecordsDB'
  private dbVersion = 3
  private storeName = 'payment_records'
  private rateSettingsStoreName = 'rate_settings'
  private db: IDBDatabase | null = null

  // 初始化数据库
  async init(): Promise<void> {
    return new Promise((resolve, reject) => {
      console.log('开始初始化IndexedDB数据库...')
      console.log('数据库名称:', this.dbName)
      console.log('数据库版本:', this.dbVersion)

      const request = indexedDB.open(this.dbName, this.dbVersion)

      request.onerror = (event) => {
        console.error('IndexedDB打开失败:', event)
        console.error('错误详情:', request.error)
        reject(new Error(`Failed to open database: ${request.error?.message || 'Unknown error'}`))
      }

      request.onsuccess = () => {
        this.db = request.result
        console.log('IndexedDB数据库初始化成功')
        console.log('数据库对象存储列表:', this.db.objectStoreNames)
        resolve()
      }

      request.onupgradeneeded = (event) => {
        console.log('IndexedDB数据库升级中...')
        const db = (event.target as IDBOpenDBRequest).result
        console.log('升级前对象存储列表:', db.objectStoreNames)

        // 创建支付记录对象存储
        if (!db.objectStoreNames.contains(this.storeName)) {
          const store = db.createObjectStore(this.storeName, { keyPath: 'id' })

          // 创建索引
          store.createIndex('member_id', 'member_id', { unique: false })
          store.createIndex('payment_date', 'payment_date', { unique: false })
          store.createIndex('status', 'status', { unique: false })
          console.log('IndexedDB支付记录对象存储创建成功')
        }

        // 创建费率设置对象存储
        if (!db.objectStoreNames.contains(this.rateSettingsStoreName)) {
          const rateStore = db.createObjectStore(this.rateSettingsStoreName, { keyPath: 'id' })

          // 创建索引
          rateStore.createIndex('member_id', 'member_id', { unique: false })
          rateStore.createIndex('created_at', 'created_at', { unique: false })
          rateStore.createIndex('updated_at', 'updated_at', { unique: false })
          console.log('IndexedDB费率设置对象存储创建成功')
        }

        console.log('升级后对象存储列表:', db.objectStoreNames)
      }
    })
  }

  // 保存支付记录
  async savePaymentRecord(record: PaymentRecord): Promise<void> {
    if (!this.db) {
      await this.init()
    }

    return new Promise((resolve, reject) => {
      console.log('开始保存支付记录到 IndexedDB:', record.id)
      const transaction = this.db!.transaction([this.storeName], 'readwrite')
      const store = transaction.objectStore(this.storeName)
      const request = store.put(record)

      request.onsuccess = () => {
        console.log('支付记录保存成功:', record.id)
        resolve()
      }
      request.onerror = (event) => {
        console.error('保存支付记录失败:', event)
        reject(new Error('Failed to save payment record'))
      }
    })
  }

  // 获取会员的支付记录
  async getPaymentRecords(memberId: string): Promise<PaymentRecord[]> {
    if (!this.db) {
      await this.init()
    }

    return new Promise((resolve, reject) => {
      console.log('开始从 IndexedDB 获取支付记录，会员ID:', memberId)
      const transaction = this.db!.transaction([this.storeName], 'readonly')
      const store = transaction.objectStore(this.storeName)
      const index = store.index('member_id')
      const request = index.getAll(memberId)

      request.onsuccess = () => {
        const records = request.result as PaymentRecord[]
        console.log(`从 IndexedDB 获取到 ${records.length} 条支付记录`)

        // 调试：打印每条记录的详情
        if (records.length > 0) {
          records.forEach((record, index) => {
            console.log(`记录[${index}]: ID=${record.id}, 类型=${record.payment_type}, 金额=${record.amount}, 会员ID=${record.member_id}`)
          })
        }

        // 按支付日期倒序排序
        records.sort((a, b) => new Date(b.payment_date).getTime() - new Date(a.payment_date).getTime())
        resolve(records)
      }

      request.onerror = (event) => {
        console.error('获取支付记录失败:', event)
        reject(new Error('Failed to get payment records'))
      }
    })
  }

  // 获取支付记录详情
  async getPaymentRecordById(id: string): Promise<PaymentRecord | null> {
    if (!this.db) {
      await this.init()
    }

    return new Promise((resolve, reject) => {
      const transaction = this.db!.transaction([this.storeName], 'readonly')
      const store = transaction.objectStore(this.storeName)
      const request = store.get(id)

      request.onsuccess = () => {
        resolve(request.result || null)
      }

      request.onerror = () => reject(new Error('Failed to get payment record'))
    })
  }

  // 更新支付记录状态
  async updatePaymentRecordStatus(id: string, status: string, isRevoked: boolean = false): Promise<void> {
    if (!this.db) {
      await this.init()
    }

    return new Promise((resolve, reject) => {
      const transaction = this.db!.transaction([this.storeName], 'readwrite')
      const store = transaction.objectStore(this.storeName)
      const getRequest = store.get(id)

      getRequest.onsuccess = () => {
        const record = getRequest.result as PaymentRecord
        if (record) {
          record.status = status
          record.is_revoked = isRevoked ? 1 : 0

          const putRequest = store.put(record)
          putRequest.onsuccess = () => resolve()
          putRequest.onerror = () => reject(new Error('Failed to update payment record'))
        } else {
          reject(new Error('Payment record not found'))
        }
      }

      getRequest.onerror = () => reject(new Error('Failed to get payment record'))
    })
  }

  // 删除支付记录
  async deletePaymentRecord(id: string): Promise<void> {
    if (!this.db) {
      await this.init()
    }

    return new Promise((resolve, reject) => {
      const transaction = this.db!.transaction([this.storeName], 'readwrite')
      const store = transaction.objectStore(this.storeName)
      const request = store.delete(id)

      request.onsuccess = () => resolve()
      request.onerror = () => reject(new Error('Failed to delete payment record'))
    })
  }

  // 清空会员的所有支付记录
  async clearMemberPaymentRecords(memberId: string): Promise<void> {
    if (!this.db) {
      await this.init()
    }

    return new Promise((resolve, reject) => {
      const transaction = this.db!.transaction([this.storeName], 'readwrite')
      const store = transaction.objectStore(this.storeName)
      const index = store.index('member_id')
      const request = index.openCursor(memberId)

      request.onsuccess = () => {
        const cursor = request.result
        if (cursor) {
          cursor.delete()
          cursor.continue()
        } else {
          resolve()
        }
      }

      request.onerror = () => reject(new Error('Failed to clear payment records'))
    })
  }

  // 获取支付记录统计
  async getPaymentStats(memberId: string): Promise<{
    total: number
    success: number
    failed: number
    pending: number
    revoked: number
    recharge: number
    deduction: number
  }> {
    const records = await this.getPaymentRecords(memberId)

    return {
      total: records.length,
      success: records.filter(r => r.status === 'success').length,
      failed: records.filter(r => r.status === 'failed').length,
      pending: records.filter(r => r.status === 'pending').length,
      revoked: records.filter(r => r.is_revoked === 1).length,
      recharge: records.filter(r => r.payment_type === 'recharge').length,
      deduction: records.filter(r => r.payment_type === 'deduction').length
    }
  }

  // 保存费率设置
  async saveRateSettings(settings: RateSettings): Promise<void> {
    try {
      if (!this.db) {
        console.log('数据库未初始化，开始初始化...')
        await this.init()
      }

      if (!this.db) {
        throw new Error('数据库初始化失败')
      }

      return new Promise((resolve, reject) => {
        console.log('开始保存费率设置到 IndexedDB:', settings.id)
        console.log('费率设置数据:', settings)

        try {
          const transaction = this.db!.transaction([this.rateSettingsStoreName], 'readwrite')
          const store = transaction.objectStore(this.rateSettingsStoreName)
          const request = store.put(settings)

          request.onsuccess = () => {
            console.log('费率设置保存成功:', settings.id)
            resolve()
          }

          request.onerror = (event) => {
            console.error('保存费率设置失败:', event)
            console.error('错误详情:', request.error)
            reject(new Error(`Failed to save rate settings: ${request.error?.message || 'Unknown error'}`))
          }
        } catch (error) {
          console.error('创建数据库事务失败:', error)
          reject(new Error(`Database transaction failed: ${error}`))
        }
      })
    } catch (error) {
      console.error('saveRateSettings 函数执行失败:', error)
      throw error
    }
  }

  // 获取会员的费率设置
  async getRateSettings(memberId: string): Promise<RateSettings | null> {
    if (!this.db) {
      await this.init()
    }

    return new Promise((resolve, reject) => {
      console.log('开始从 IndexedDB 获取费率设置，会员ID:', memberId)
      const transaction = this.db!.transaction([this.rateSettingsStoreName], 'readonly')
      const store = transaction.objectStore(this.rateSettingsStoreName)
      const index = store.index('member_id')
      const request = index.get(memberId)

      request.onsuccess = () => {
        const settings = request.result as RateSettings | null
        console.log('获取费率设置结果:', settings)
        resolve(settings)
      }
      request.onerror = (event) => {
        console.error('获取费率设置失败:', event)
        reject(new Error('Failed to get rate settings'))
      }
    })
  }

  // 删除会员的费率设置
  async deleteRateSettings(memberId: string): Promise<void> {
    if (!this.db) {
      await this.init()
    }

    return new Promise((resolve, reject) => {
      console.log('开始删除费率设置，会员ID:', memberId)
      const transaction = this.db!.transaction([this.rateSettingsStoreName], 'readwrite')
      const store = transaction.objectStore(this.rateSettingsStoreName)
      const index = store.index('member_id')
      const request = index.getKey(memberId)

      request.onsuccess = () => {
        const key = request.result
        if (key) {
          const deleteRequest = store.delete(key)
          deleteRequest.onsuccess = () => {
            console.log('费率设置删除成功:', memberId)
            resolve()
          }
          deleteRequest.onerror = (event) => {
            console.error('删除费率设置失败:', event)
            reject(new Error('Failed to delete rate settings'))
          }
        } else {
          console.log('费率设置不存在，无需删除:', memberId)
          resolve()
        }
      }
      request.onerror = (event) => {
        console.error('查找费率设置失败:', event)
        reject(new Error('Failed to find rate settings'))
      }
    })
  }
}

// 创建数据库实例
const paymentDB = new PaymentDatabase()

// 导出数据库函数
export async function savePaymentRecord(record: PaymentRecord): Promise<void> {
  await paymentDB.savePaymentRecord(record)
}

export async function getPaymentRecords(memberId: string): Promise<PaymentRecord[]> {
  return await paymentDB.getPaymentRecords(memberId)
}

export async function getPaymentRecordById(id: string): Promise<PaymentRecord | null> {
  return await paymentDB.getPaymentRecordById(id)
}

export async function updatePaymentRecordStatus(id: string, status: string, isRevoked: boolean = false): Promise<void> {
  await paymentDB.updatePaymentRecordStatus(id, status, isRevoked)
}

export async function deletePaymentRecord(id: string): Promise<void> {
  await paymentDB.deletePaymentRecord(id)
}

export async function clearMemberPaymentRecords(memberId: string): Promise<void> {
  await paymentDB.clearMemberPaymentRecords(memberId)
}

export async function getPaymentStats(memberId: string): Promise<{
  total: number
  success: number
  failed: number
  pending: number
  revoked: number
  recharge: number
  deduction: number
}> {
  return await paymentDB.getPaymentStats(memberId)
}

// 费率设置相关函数
export async function saveRateSettings(settings: RateSettings): Promise<void> {
  await paymentDB.saveRateSettings(settings)
}

export async function getRateSettings(memberId: string): Promise<RateSettings | null> {
  return await paymentDB.getRateSettings(memberId)
}

export async function deleteRateSettings(memberId: string): Promise<void> {
  await paymentDB.deleteRateSettings(memberId)
}

// 测试数据库连接
export async function testDatabaseConnection(): Promise<boolean> {
  try {
    console.log('开始测试数据库连接...')
    await paymentDB.init()

    // 尝试创建一个测试记录，使用随机ID避免冲突
    const testSettings: RateSettings = {
      id: `test_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
      member_id: `test_member_${Date.now()}`,
      exchange_rate: '0.052',
      created_at: new Date().toISOString(),
      updated_at: new Date().toISOString()
    }

    await paymentDB.saveRateSettings(testSettings)
    console.log('数据库连接测试成功')
    return true
  } catch (error) {
    console.error('数据库连接测试失败:', error)
    return false
  }
}

export default paymentDB 